package cacco.jp.mld;

import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import cacco.jp.mld.panel.entity.LogEntity;
import cacco.jp.mld.panel.entity.UserEntity;
import cacco.jp.mld.panel.form.JqgridResponse;
import cacco.jp.mld.panel.service.LogService;

@RequestMapping(value = "/logs")
@Controller
public class LogController {

	private static final Logger logger = LoggerFactory
			.getLogger(LogController.class);

	@Autowired
	private LogService logService;

	/**
	 * Simply selects the home view to render by returning its name.
	 */
	@RequestMapping(method = RequestMethod.GET)
	public String listHome(ModelMap map, HttpServletRequest request) {
		UserEntity entity = (UserEntity) request.getSession()
				.getAttribute("aa");
		map.addAttribute("session", entity);
		System.out.println(entity);

		return "log/logs";
	}

	@RequestMapping(value = "/listgrid", method = RequestMethod.GET, produces = "application/json")
	@ResponseBody
	public JqgridResponse<LogEntity> listGrid(
			@RequestParam(value = "page", required = false) Integer page,
			@RequestParam(value = "rows", required = false) Integer rows,
			@RequestParam(value = "sidx", required = false) String sortBy,
			@RequestParam(value = "sord", required = false) String order,
			@RequestParam("_search") Boolean search) {

		logger.info("Listing items for grid with page: {}, rows: {}", page,
				rows);
		logger.info("Listing items for grid with sort: {}, order: {}", sortBy,
				order);

		List<LogEntity> list = null;
		list = logService.getAlByPage(rows, page, sortBy, order);
		JqgridResponse<LogEntity> response = new JqgridResponse<LogEntity>();
		int totalRecords = logService.getTotalRecords();
		int total = totalRecords % rows == 0 ? (int) Math.ceil(totalRecords
				/ rows) : (int) Math.ceil(totalRecords / rows) + 1;

		logger.info("Listing logs for grid with total rows {}", list.size());
		response.setRecords(list);
		response.setTotalRecords(totalRecords);
		response.setTotalPages(total);
		response.setCurrentPage(page);
		return response;
	}

}
